package com.etone.smartAudit.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.etone.smartAudit.annotation.AdminOperation;
import com.etone.smartAudit.annotation.LoginAdmin;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.dto.LoginDTO;
import com.etone.smartAudit.dto.egcc.SubscriptDTO;
import com.etone.smartAudit.dto.egcc.VerifyTokenDTO;
import com.etone.smartAudit.service.AdminService;
import com.etone.smartAudit.service.AuthService;
import com.etone.smartAudit.service.EGCCMService;
import com.etone.smartAudit.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.handler.RequestMatchResult;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.RandomAccessFile;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author: 蒋学伟
 * @date: 2018-10-12 09:45:37
 * @description:
 */
@AllArgsConstructor
@RestController
@Api(tags = "鉴权", value = "Auth")
public class AuthController {

    private AdminService adminService;

    private AuthService authService;


    private WebApplicationContext applicationContext;

    @AdminOperation(item = "登录", module = "系统登录", content = "登录系统")
    @PostMapping("/auth/login")
    @ApiOperation(value = "登陆授权")
    public LoginVO login(@RequestBody @Validated LoginDTO loginDTO) {
        return adminService.login(loginDTO, true);
    }

    @PostMapping("/auth/login/gmcc/portal")
    @ApiOperation(value = "移动单点登陆")
    public LoginVO gmccPortalLogin(HttpServletRequest request) {

        return adminService.gmccPortalLogin(request);
    }

    @PostMapping("/auth/login/gmcc/ezt")
    @ApiOperation(value = "E掌通单点登陆")
    public LoginVO gmccElLogin(@RequestBody VerifyTokenDTO dto) {

        return adminService.getEztLogin(dto);
    }

    @AdminOperation(item = "退出", module = "系统登录", content = "退出系统")
    @PostMapping("/auth/logout")
    @ApiOperation(value = "退出操作")
    public void logout(@ApiIgnore @LoginAdmin Admin admin) {
        adminService.logout(admin);
    }

    @GetMapping("/auth/verify.png")
    @ApiOperation(value = "验证码")
    public void verifyCode(
            @ApiParam(value = "图片长度（图片长宽比为3:1），默认长度为120") @RequestParam(required = false, defaultValue = "120") Integer width,
            @ApiParam(value = "图片干扰复杂度，最大10，默认5") @RequestParam(required = false, defaultValue = "5") Integer complexity,
            @ApiParam(value = "随机值") @RequestParam() String uuid,
            HttpServletResponse response
    ) {
        authService.getVerifyCode(width, complexity, uuid, response);
    }

    @GetMapping("/auth/allInterface")
    public List<Map<String, String>> getAllInterface(HttpServletRequest request) {

        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        List<RequestMappingInfo> mList = new ArrayList<>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> mapone = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            handMethod(method);
            RequestMappingInfo last = info.getMatchingCondition(request);
            if (last != null) {
                mList.add(last);
            }

            RequestMethodsRequestCondition methodsRequestCondition = info.getMethodsCondition();
            Set<RequestMethod> methods = methodsRequestCondition.getMethods();
            String methodName = "";
            for (RequestMethod requestMethod : methods) {
                methodName = requestMethod.toString();
            }
            // 获取url
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                mapone.put("url", url);
            }
            // 反射获取url对应类名和方法名
            mapone.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
            mapone.put("method", method.getMethod().getName()); // 方法名
            // 获取请求类型

            for (RequestMethod requestMethod : methodsRequestCondition.getMethods()) {
                mapone.put("type", requestMethod.toString());
            }
            list.add(mapone);
        }
        return list;
    }

    private void handMethod(HandlerMethod handlerMethod) {
        Method method = handlerMethod.getMethod();
        //获取接口名称
        Annotation[] declaredAnnotations = method.getDeclaredAnnotations();

        //获取接口返回数据
        Class  clazz = method.getReturnType();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f:declaredFields) {
            System.out.println(f.getName());
        }
        //获取接口参数
        Class<?>[] parameterTypes = method.getParameterTypes();
        //获取请求sql
        //获取接口使用到的表
    }
}